<script setup>
/* eslint-disable */
import { onMounted, defineProps, ref, reactive } from 'vue'

import { useIntervalFn } from '@vueuse/core'

import PPixel from '@/comps/PPixel'

import { get, post } from '@/request.js' 

const SIZE = 10

const props = defineProps(['value'])

const grid = reactive(Array(SIZE * SIZE).fill({color: 0, owner: ''}))
var nft = reactive({})
const updateGrid = async () => {
  const res = await get('nft')
  var grids = res.data.grids
  for(const g of grids ){
    grid[g.idx] = g
  }
  nft = res.data.nft[0]
  localStorage.setItem('nftId', nft._id)
}

onMounted(updateGrid)
// useIntervalFn(updateGrid, 1000)

const click = async (x, y) => {
  const owner = localStorage.getItem('address')
  const idx = x * SIZE + y
  if (grid[idx].color != 0) {
    alert('This one has been assigned already.')
    return
  }
  
  const color = props.value
  const nftId = nft._id
  const data = {
    "x": x,
    "y": y,
    "idx": idx,
    "color": color,
    "owner": owner,
    "nftId": nftId
  }
  grid[idx] = data
  const res = await post('nft/grid', data)
  if (res.status === 201) {
    alert('You have successfully colored the pixel.')
  }
  await updateGrid()

}


</script>

<template>
    <div class="artboard__row" v-for="(_, x) in SIZE" :key="x">
    <template v-for="(_, y) in SIZE" :key="y">
      <PPixel
        :color="grid[(x * SIZE) + y].color" @click="click(x, y)"
        :account="`${grid[(x * SIZE) + y].owner}`"
      />
    </template>
  </div>

</template>

<style>
  .artboard__row {
    height: 20px;
  }

  .tooltip:hover {
    z-index:1;
    color:#8325f7;
    position:relative;
  }

  .tooltip:after {
    content: attr(tip);
    font-size: 90%;
    line-height: 1.2em;
    color: #000;
    padding: 5px 10px;
    -moz-border-radius: 6px;
    -webkit-border-radius: 6px;
    border-radius: 6px;
    background: #ddd;
    position: absolute;
    top: -2px;
    left: 25px;
    display: none;
    white-space: nowrap;
    opacity: 75%;
  }

  .tooltip:hover:after {
    display:block;
  }
</style>
